// 代码审查的js
(function(){
				
	// ============================ 行数计算及高亮 =============================
	$('pre code').each(function(i, block) {
		
		var ele = $(block);
		var content = ele.html();
		
		hljs.highlightBlock(block);
		//hljs.lineNumbersBlock(block);
		var codeHtmlEle = $('#code-html');
		var lineEle = $("#sourcecode_line");
		lineEle.height(codeHtmlEle.height()-25);
		// 右侧备注信息容器,计算宽度
		var noteshowParDiv = $('.notesshow_container_pardiv');
		if(noteshowParDiv.height()<codeHtmlEle.height()-25){
			noteshowParDiv.height(codeHtmlEle.height()-5);
		}		
		
		var endWith = function(str, s){
			if (s==null || s=="" || str.length==0 || s.length > str.length) {
				return false;
			}
			if(str.substring(str.length-s.length)== s){
				return true;
			} 
			return false;
		}
		var str = lineEle.text(); //会对html字符进行转义
		var strstr = str.replace(/\r/gi,"");
		var strstrArrs = strstr.split("\n"); 
		var n = strstrArrs.length; 
		var notelinecount = 0;
		var codelinecount = 0;
		var blanklinecount = 0; //空行
		var mulline = false;
		for(var i=0;i<n;i++){
			var lineStr = strstrArrs[i].trim();
			if(lineStr.indexOf('/*')==0 || lineStr.indexOf('<\%--')==0 ){
				if(endWith(lineStr, '*/') || endWith(lineStr, '--%>')){ //单行
					mulline = false;
				} else {
					mulline = true; //多行注释
				}
				notelinecount ++;
			} else if(endWith(lineStr, '*/') || endWith(lineStr, '--%>')){ //多行注释结束
				mulline = false;
				notelinecount ++;
			} else if(lineStr.indexOf('*')==0){
				notelinecount ++;
			} else if(lineStr.indexOf('//')==0){ //单行注释
				notelinecount ++;
			} else if(lineStr.indexOf('<!--')==0){ //单行注释
				notelinecount ++;
			} else if(lineStr.indexOf(';//')>0){ //中间
				notelinecount ++;
				codelinecount++;
			} else if(lineStr.indexOf(' //')>0){ //中间
				notelinecount ++;
				codelinecount++;
			} else if(mulline){
				notelinecount ++;
			} else if(!lineStr) { //空行
				blanklinecount++;
			} else { // 代码
				codelinecount++;
			}
			
		}
		
		$(".linecount").text(n); //总行数
		$(".notelinecount").text(notelinecount); //注释总行数
		$(".codelinecount").text(codelinecount); //代码总行数
		$(".blanklinecount").text(blanklinecount); //空行总行数
		
		line(lineEle, n); 
				
		function line(ele, n){
			var num = "";
			for (var i=1;i<=n;i++) { 
				if (document.all) { 
					num += i+"\r\n"; 
				} else { 
					num += i+"\n"; 
				} 
			}
			ele.val(num);
		}
	});
	$('.cr-content').css('paddingTop', $(".panel-heading").outerHeight(true));
	
	// ============================ 主题切换JS =============================
	$('#themeselect').change(function(){
		var theme = $(this).val();
		switchSkin(theme);
	}); 
	function switchSkin(skinName, setVal){
		if(setVal){
			$('#themeselect').val(skinName); //设置
		}		
		$("#cssfile").attr('href', 'https://cdn.staticfile.org/highlight.js/10.1.2/styles/'+skinName+'.min.css');
		if($.cookie){ //设置cookie
			$.cookie("codereview_Skin", skinName, {path:'/', expires:3650});
		}
		
	}
	if($.cookie){ //设置cookie
		var cookie_skin=$.cookie("codereview_Skin");
		if(cookie_skin){
			switchSkin(cookie_skin, true);
		}
	}
	// ============================ 代码审查 =============================
	// 备注数据数组 
	var notesdata = [
		{'nid':'199693902750416896', 'keyid':"id123",'keycode':{"startMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":230},"endMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":248},"text":"GitCommitInfoModel","id":"id123"}, 'remarks':'123', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-05 09:12:17.0'},
		{'nid':'199764051566264320', 'keyid':"h1625464240253",'keycode':{"startMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":395},"endMeta":{"parentTagName":"SPAN","parentIndex":11,"textOffset":4},"text":"List<GitCommitInfoModel> list","id":"h1625464240253"}, 'remarks':'list师傅的说的浮士德发送的list<span>', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-05 13:51:01.0'},
		{'nid':'200047542438723584', 'keyid':"h1625531818784",'keycode':{"startMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":242},"endMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":265},"text":"oModel> getPageCommits(","id":"h1625531818784"}, 'remarks':'测试重叠的', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-06 08:37:31.0'},
		{'nid':'200048403558694912', 'keyid':"h1625532048265",'keycode':{"startMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":224},"endMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":275},"text":" List<GitCommitInfoModel> getPageCommits(HttpServle","id":"h1625532048265"}, 'remarks':'再来一层', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-06 08:40:56.0'},
		{'nid':'200059864871862272', 'keyid':"h1625534779832",'keycode':{"startMeta":{"parentTagName":"SPAN","parentIndex":23,"textOffset":0},"endMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":481},"text":"if (gitinfo != null)","id":"h1625534779832"}, 'remarks':'if空指针', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-06 09:26:29.0'},
		{'nid':'200089992565882880', 'keyid':"h1625541958792",'keycode':{"startMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":476},"endMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":480},"text":"null","id":"h1625541958792"}, 'remarks':'空空如也', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-06 11:26:12.0'},
		{'nid':'200417379803463680', 'keyid':"h1625620022472",'keycode':{"startMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":293},"endMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":308},"text":"WtGitInfoModel ","id":"h1625620022472"}, 'remarks':'浮士德', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-07 09:07:07.0'},
		{'nid':'200532938884907008', 'keyid':"h1625647570631",'keycode':{"startMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":3827},"endMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":3862},"text":"WtGitInfoModel gitinfo, QueryParams","id":"h1625647570631"}, 'remarks':'好高好高的高度', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-07 16:46:18.0'},
		{'nid':'200790289835622400', 'keyid':"h1625708918672",'keycode':{"startMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":5377},"endMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":5850},"text":" Integer pageNum = (params.getPageNum() == null || params.getPageNum() <= 0) ? 1 : params.getPageNum();\r\n                params.setPageNum(pageNum);\r\n                list = GitUtil.getGitVersions(localPath, projectName, params);\r\n                log.warn(\"统计{}项目提交记录完成！\", projectName);\r\n                setRequestAttriList(request, list); // 放到request中\r\n            } catch (GitAPIException | JgitNologException | IOException e) {\r\n                log.error(\"\", e);\r\n            }","id":"h1625708918672"}, 'remarks':'大伙来了，地方士大夫士大夫士大夫的，士大夫是否为士大夫士大夫，时代氛围浮士德发随碟附送的发生的', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-08 09:48:56.0'},
		{'nid':'200903153648926720', 'keyid':"h1625735829929",'keycode':{"startMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":230},"endMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":248},"text":"GitCommitInfoModel","id":"h1625735829929"}, 'remarks':'GModel,再次选中试试', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-08 17:17:24.0'},
		{'nid':'201265879839670272', 'keyid':"h1625822310659",'keycode':{"startMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":395},"endMeta":{"parentTagName":"SPAN","parentIndex":20,"textOffset":4},"text":" List","id":"h1625822310659"}, 'remarks':'list师傅的说的浮士德发送的list', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-09 17:18:45.0'},
		{'nid':'201266937446006784', 'keyid':"h1625822566010",'keycode':{"startMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":461},"endMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":468},"text":"if (git","id":"h1625822566010"}, 'remarks':'list师傅的说的浮士德发送的list', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-09 17:22:57.0'},
		{'nid':'201267899694841856', 'keyid':"h1625822798140",'keycode':{"startMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":666},"endMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":681},"text":"Integer pageNum","id":"h1625822798140"}, 'remarks':'list师傅的说的浮士德发送的list', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-09 17:26:47.0'},
		{'nid':'202221342060183552', 'keyid':"h1626050115124",'keycode':{"startMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":1408},"endMeta":{"parentTagName":"CODE","parentIndex":0,"textOffset":1426},"text":"GitCommitInfoModel","id":"h1626050115124"}, 'remarks':'list师傅的说的浮士德发送的list', 'userid':2, 'username':'超级管理员', 'createtime':'2021-07-12 08:35:25.0'}
	];
	
	//高亮区右键事件
	if ($("#oacodereview_check_popmenu").length==0) { 
		$("body").append('<div class="contextMenu" id="oacodereview_check_popmenu" style="position: absolute;display: none;">' +
			'	<ul>' +
			'		<li id="oacodereview_noteadd">添加备注</li>' +
			'		<li id="oacodereview_noteupd">修改备注</li>' +
			'		<li id="oacodereview_notedel">删除备注</li>' +
			'	</ul>' +
			'</div>');
	}
	var isOpening = false; //窗口是否打开，用于打开唯一窗口
	// 打开备注窗口
	var openAddCodeNoteDialog = function(ele, keytype, url, params, title) {
		if(!isOpening){ // 未打开再执行，确定只打开一个窗口
			params.cvid =cvid; //业务id传递，保存数据库时用 
			isOpening = true;
			var options = {area: '600px'};
			$("#addTouchNote").modal('show');
			$("#addTouchNote").find("[name]").val("");
			$("#addTouchNote").find("#keytype").val(keytype); //操作类型，添加还是修改
			$("#addTouchNote").find(".showtext").text("");
			$("#addTouchNote").find(".showtext").text(params.text);
			$("#addTouchNote").find("#addTouchNoteTitle").text(title); //标题修改
			for(key in params){ //赋值		
				$("#addTouchNote").find("[name='"+key+"']").val(params[key]);
			}			
		}		

	}			
	$('#addTouchNote').on('hide.bs.modal', function() {
        isOpening = false; //完成,防止打开多个页面，其实不处理也可以bs本身处理过了
    });
	
	var codeEle = $('#code-html'); //代码容器	
	var cvid = codeEle.data("cvid"); //审查代码id,用于数据库保存时确定业务id	
	
	// 备注区元素的处理备注修改、删除，左键双击,为修改
	var noteEleBindFn = function(ele){
		var $this = ele;
		$this.off("delete").on("delete", function(){ //重写删除方法
			Touchjs.confirm("删除备注", "确定要删除该备注吗？", function(){
				// 可能需要需要后台交互，请重写 
				var params = {id:$this.data("nid")}; // 业务id传递
				
				touchNote.removeHighlight(codeEle, $this.data("keycode").id, function(toRemoves, idToUpdates, extraToUpdates){
					// 修改鼠标悬停提示
					if(idToUpdates){
						
						$.each(idToUpdates, function(i, n){
							
							var dataset = n.dataset;
							var id = $(n).attr('data-'+touchNote.DATA_ID);
							$(n).attr("data-target", '.content_codetips_'+id);
							$(n).data("target", '.content_codetips_'+id);
							
							$(n).removeClass("shieldMarked_touchjs-tips"); //移除样式，重新绑定
							
							Touchjs.load(codeEle, ['tips']);
							
						});
					}
					
				});
				var containerEle = $(codeEle.getOptions("noteContainerSelector"));
				//var index = containerEle.find("."+codeEle.getOptions('noteItemClsName')).index($this);
				//var count = containerEle.find("."+codeEle.getOptions('noteItemClsName')).length;				
				
				$this.remove();
				// 更新备注总数 
				containerEle.triggerHandler("refreshCount");
				
			});			
		}).contextMenu('oacodereview_check_popmenu', { // 右键
			onContextMenu: function(e) {
				return true;
			},
			onShowMenu: function(e, menu) {
				// 不可添加，可删除修改
				$('#oacodereview_noteadd', menu).remove();
				return menu;
			},
			bindings: {
				'oacodereview_noteupd': function(t) { // 修改
					$this.triggerHandler("update");
				},
				'oacodereview_notedel': function(t) { // 删除
					$this.triggerHandler("delete");
				}
			}		
		});
	}
	
	// 高亮区元素的处理备注修改、删除，左键双击,为修改
	var highlightEleBindFn = function(ele, codeEle){
		var noteItemClsName = codeEle.getOptions('noteItemClsName');
		// 高亮元素的处理备注修改、删除，左键双击,为修改，！！！注意！！！：修改删除一般要与后台交互，需要自行修改			
		var $this = ele;
		$this.on("update", function(){ //修改
			var keyid = $this.data(touchNote.DATA_ID);			
			$("."+noteItemClsName+"[data-keyid='"+keyid+"']").triggerHandler("update"); //点击
		}).on("delete", function(){ //删除
			var keyid = $this.data(touchNote.DATA_ID);
			$("."+noteItemClsName+"[data-keyid='"+keyid+"']").triggerHandler("delete"); //点击
		}).on("click", function(){ //与右侧备注区对应
			var keyid = $this.data(touchNote.DATA_ID);				
			$("."+noteItemClsName+"[data-keyid='"+keyid+"']").click(); //点击
		}).on("dblclick", function(){ //双击=修改
			$this.triggerHandler("update");
		}).contextMenu('oacodereview_check_popmenu', { // 右键
			onContextMenu: function(e) {
				return true;
			},
			onShowMenu: function(e, menu) {
				// 不可添加，可删除修改
				$('#oacodereview_noteadd', menu).remove();
				return menu;
			},
			bindings: {
				'oacodereview_noteupd': function(t) { // 修改
					$this.triggerHandler("update");
				},
				'oacodereview_notedel': function(t) { // 删除
					$this.triggerHandler("delete");
				}
			}
		});
	}
	
	
		//console.log(notesdata)
	codeEle.touchNote({
		root:codeEle[0],
		/** 父节点选择器，只有符合选择器的才作为父节点 */
		parSelectors : 'code', // 父节点，作为位置偏移的基准，保存后不可改变，否则可能影响定位
		hldatas : notesdata, //初始化数据	
		// dom节点元素高亮处理后的处理
		highlightNoteAfter:function(hlele, noteEle, data, tipsClass, tipsContentClass, containerE, options){
			// 添加鼠标悬停提示内容区
			var nid = data.nid;
			var keycode = data.keycode;
			var remarks = data.remarks;
			var userid = data.userid;
			var username = data.username;
			var createtime = data.createtime;
			hlele.addClass('touchjs-tips').attr('data-target', '.'+tipsContentClass).attr('data-tips-class', 'darkcyan')
				.attr('data-width','250'); //添加样式
			var tipsContainerEle = $(".tips_container"); //提示容器
			// 内容区，如果已经存在则不再添加
			var tipsEle = tipsContainerEle.find('.'+tipsContentClass);
			if(!tipsEle.length){ // 
				var html = '<div style="display: none;" class="'+tipsContentClass+'">'+
					'<h5>'+username+'：</h5>'+
					remarks+'<br>'+
					'<span class="touchjs-fmttime " data-fromnow="show">' + createtime + '</span></div>';
				tipsContainerEle.append(html);				
			}
			
			// 备注区处理
			noteEle.find(".createtime").each(function(i,n){ //时间格式处理
				$(this).addClass("touchjs-fmttime");
			});
			noteEleBindFn(noteEle); //备注区函数处理
			
			highlightEleBindFn(hlele, codeEle); //高亮区函数处理
			
			// 加载
			Touchjs.load($('body'), ['fmttime','tips']);
		},
		// 右侧备注区条目选中样式
		noteSelectedClsName:'panel-primary',
		// 打开弹出框操作
		openDialog : function(ele, key, url, params, title) {
			openAddCodeNoteDialog(ele, key, url, params, title);
		}	
	});
	
	// 保存选区
	$('.submitbtn').click(function(){
		var remarks = $("textarea[name='remarks']").val();
		var keytype = $("#keytype").val(); //操作类型
		if(keytype == touchNote.OPERATE_Type.UPDATE){ //修改		
			// 将备注区内容修改了，生产环境中是与后台交互
			var keyid = $("input[name='keyid']").val(); // 获取keyid
			var noteItemClsName = codeEle.getOptions('noteItemClsName'); // 获取对应的备注区
			$("."+noteItemClsName+"[data-keyid='"+keyid+"']").find('.remarks').text(remarks); //点击
			
		} else if(keytype == touchNote.OPERATE_Type.ADD){ //添加
			var nodes = codeEle.addHighlighter(remarks);
			console.log(nodes);
		}
		
		$("#addTouchNote").modal('hide');
	});
	
	// 触发滚动，以便刷新时显示在正常位置
	$(window).triggerHandler('scroll.touchnote');
	
})();